import pythoncom
import xlwings as xw

from config import SrcContext, TABLE_HEADER


class STORAGE:
    wb = xw.Book
    active_sht = xw.Sheet

    def __init__(self, book):
        pythoncom.CoInitialize()
        self.wb = book
        self.wb.app.visible = False
        self.wb.app.display_alerts = False
        self.wb.app.screen_updating = False

    '''
    {
        sht_name: xxx,
        sht_ctx: list[SrcContext]
    }
    '''
    def process(self, sht_ctx: dict):
        for name, lst in sht_ctx.items():
            self.addSheet(name)
            for item in lst:
                self.addLine(item)

    def addLine(self, rec_ctx: SrcContext):
        self.active_sht.api.Rows(2).Insert()
        line = [rec_ctx.page_url, rec_ctx.product_title,
                rec_ctx.product_price, rec_ctx.description,
                rec_ctx.create_time, rec_ctx.category,
                rec_ctx.pic_1, rec_ctx.pic_2,
                rec_ctx.pic_3, rec_ctx.pic_4,
                rec_ctx.pic_5,
                rec_ctx.size, rec_ctx.color]
        self.active_sht.range("A2").value = line

    def addSheet(self, sht_name: str):
        s = self.wb.sheets.add(sht_name)
        s.range("A1").value = TABLE_HEADER
        s.range('A1:M1').api.Borders(7).LineStyle = 1
        s.range('A1:M1').api.Borders(7).Weight = 3
        s.range('A1:M1').api.Borders(8).LineStyle = 1
        s.range('A1:M1').api.Borders(8).Weight = 3
        s.range('A1:M1').api.Borders(9).LineStyle = 1
        s.range('A1:M1').api.Borders(9).Weight = 3
        s.range('A1:M1').api.Borders(10).LineStyle = 1
        s.range('A1:M1').api.Borders(10).Weight = 3
        self.active_sht = s

    def setSheet(self, sht_name: str):
        self.active_sht = self.wb.sheets[sht_name]

    # ? throw error
    # def __del__(self):
    #     pythoncom.CoUninitialize()
